$(function(){
	$.extend(cms, {
		Issuu : {
			inicheck : true,
			total : 0,
			startIndex : 0,
			pageSize : 10,
			param : [],
			setParam : function(data){
				this.param = data;
			},
                        updateURLDocument : function() {
                            var that = this,
                            data = that.param;
                            $('#ipDocsMediaDisplay').html(data.media.html);
                            $('#ipDocsId').val(data.url);
                            $('#ipDocsImages').val(data.images[0].url);
                            $('#ipDocsMedia').val(escape(data.media.html));
                            $('#txtTitle').val(data.title);
                            $('#textaDescription').val(data.description);
                            $('#txtlinkurl').val('URL link to your song, fan page, site');
                            $('#txtLinkTitle').val('Visit our site, download our song, buy our product');
                            var kw = '';
                            for (var i = 0; i < data.keywords.length; i++) {
                                    kw += ('<option value="'+data.keywords[i].name+'" selected="selected" >'+data.keywords[i].name+'</option>');
                            };
                            $('#selId-keyword').html(kw);
                            
                            /*var ct = '';
                            for (var i = 0; i < window.categorys.length; i++) {
                                ct += ('<option value="'+window.categorys[i].id+'">'+window.categorys[i].title+'</option>');
                            }
                            $('#selCategory').html(ct);
                            
                            var co = '';
                            for (var i = 0; i < window.countries.length; i++) {
                                co += ('<option value="'+window.countries[i].id+'">'+window.countries[i].title+'</option>');
                            }
                            $('#selCountries').html(co);*/
                            
                            $('#campaign_gender_a').prop('checked', true);
                            
                            $('.img-tab0').attr('src',data.images[0].url);
                            $('.img-tab1').attr('src',data.images[0].url);
                            $('.img-tab2').attr('src',data.images[0].url);
                            $('.img-tab3').attr('src',data.images[0].url);
                            $('.img-tab4').attr('src',data.images[0].url);
                            $('#campaign_unformatted_budget').val('500.00');
                            $('#campaign_budget_kind').val('lifetime');
                            $('#max_bid').val('13');
                            $('.sel-chosen').chosen();
                            $.fancybox.close();
                            
                        },
			initData : function(){
				var that = this,
                                response = that.param;
				// console.log(response.docs.length);return false;
                                if ($("#id").length > 0) {
                                    html = 
                                        ('<a href="javascript: void(0);" onclick="cms.Issuu.updateURLDocument();" title="'+response.title+'" alt="">')+
                                                ('<div class="divCls-Group-issuu">')+
                                                                ('<img src="'+response.images[0].url+'" title="'+response.title+'" alt="" />')+
                                                                ('<div class="divCls-title">'+response.title+'</div>')+
                                                ('</div>')+
                                        ('</a>');
                                
                                } else {
                                html = 
                                        ('<a href="'+window.site.app.base_url+'Promote-Document/docsUrl/'+response.url+'" title="'+response.title+'" alt="">')+
                                                ('<div class="divCls-Group-issuu">')+
                                                                ('<img src="'+response.images[0].url+'" title="'+response.title+'" alt="" />')+
                                                                ('<div class="divCls-title">'+response.title+'</div>')+
                                                ('</div>')+
                                        ('</a>');
                                }
                                
				if (this.inicheck)
				{
					var phantrnang = that.pagination(response.numFound, 0, 'Next');
					this.inicheck = false;
				}
				$('#results').empty().append(html);
				$('#results').after(phantrnang);
			},
			pagination : function(count, page, type){
				this.total = count;
				page = (page < 0 ) ? 0 : page;
				var that = this, html ='', total=0, start=0, stop = 10;
				start = page*10;
				stop = page*10 + 10;
				stop = (stop > count/100) ? count/100 : stop ;
				if (count)
				{
					
					html += 
						('<div class="pagination pagination-centered">')+
							('<ul>')+
								('<li><a class="pagination-prev" data-page="'+start+'" href="#">Prev</a></li>');
						for (var i = start; i < stop; i++) {
					html += 	('<li class="'+(type=='Next' ? (i==start ? 'active' : '') : (i==(stop-1) ? 'active' : ''))+'" ><a class="pagination-ele-i" href="javascript:;" data-page="'+(i*10)+'" >'+(i+1)+'</a></li>');
							};
					html+=		('<li><a class="pagination-next" data-page="'+stop+'" href="#">Next</a></li>')+
							('</ul>')+
						('</div>');
				}
				return html;
			},
			setKeyword : function(str) {
				if (str.indexOf('http://')!=-1) {
					str = php.str_replace('http://','', str);
				}
				if (str.indexOf('https://')!=-1)
				{
					str = php.str_replace('http://','', str);
				}
				if (str.indexOf('issuu.com/')!=-1)
				{
					str = php.explode('/', str);
					str = typeof(str[1])=='undefined' ? str[0] : 'username:'+str[1];
				}
				return str;
			},
			search : function(){
				var input_url = $('#inputIdValSearch').val(), that = this;
				//query = cms.Issuu.setKeyword(query);
                                //var input_url = 'http://techcrunch.com/2013/03/26/embedly-now-goes-beyond-embedding-with-new-products-extract-display-for-making-sense-of-links-resizing-images/';
                                var embedlyAPI = "http://api.embed.ly/1/extract?key=3cf956e59ecc4ba185ab7ed8301f4a61&url="+escape(input_url);
				var request = $.ajax({
                                        url: embedlyAPI,
					dataType: 'json', // Choosing a JSON datatype
					beforeSend : function() {
						cms.jsloading();
					},
					success : function(data){
						cms.Issuu.setParam(data);
						cms.Issuu.initData();
						cms.jsloading(1);
					},
					error: function(x, t, m){
                                                var error_list = new Array("error", "abort", "timeout", "parsererror");
						if(error_list.indexOf(t) !== -1)
						{     
                                                        //cms.Issuu.search();
							cms.jsloading(1);
							alert('Looking back, it seems we can not find what you are looking for or network is slow. Please try agian');
							request.abort();
						}
					},
				});
			},
			even : function() {
				var that =this;
				$('.pagination-ele-i').live('click', function(){
					$(this).parent().parent().find('li').removeClass('active');
					$(this).parent().addClass('active');
					that.startIndex = $(this).data('page');
					that.search();
					return false;
				});
				$('.pagination-next').live('click', function(e){
					e.preventDefault();
					var ele = '', _this = this;
					$.each($('.pagination-ele-i'), function(){
						var parent = $(this).parent();
						if ( parent.hasClass('active') && parent.next().text() != 'Next' ) {
							parent.parent().find('li').removeClass('active');
							parent.next().addClass('active');
							that.startIndex = parent.next().find('a').data('page');
							that.search();
							return false;
						}
						else if ( parent.hasClass('active') && parent.next().text() == 'Next' )
						{
							if ( parseInt($(_this).data('page')) == parseInt(parent.text()) )
							{
								page = parseInt($(_this).data('page'))/10;
								that.startIndex = $(_this).data('page');
								that.search();
								$('.pagination-centered').empty().append(cms.Issuu.pagination(cms.Issuu.total,page, 'Next'));
								return false;
							}
						}
					})
					return false;
				});
				$('.pagination-prev').live('click', function(e){
					e.preventDefault();
					var ele = '', _this = this;
					$.each($('.pagination-ele-i'), function(){
						var parent = $(this).parent()
						if ( parent.hasClass('active') && parent.prev().text() != 'Prev' ) {
							parent.parent().find('li').removeClass('active');
							parent.prev().addClass('active');
							that.startIndex = parent.prev().find('a').data('page');
							that.search();
							return false;
						}
						else if ( parent.hasClass('active') && parent.prev().text() == 'Prev' )
						{
							if ( parseInt($(_this).data('page')) == parseInt(parent.text())-1 )
							{
								page = parseInt($(_this).data('page'))/10-1;
								if ( page < 0 ) return false;
								that.startIndex = page*10;
								that.search();
								$('.pagination-centered').empty().append(cms.Issuu.pagination(cms.Issuu.total,page, 'Prev'));
								return false;
							}
						}
					})
					return false;
				});
			}
		}
	})
	$('.inputCls-button-search').click(function(){
		cms.Issuu.search();
		return false;
	});
	$(window).on('keyup', function(e){
        e.preventDefault();
        if (e.which == 13) cms.Issuu.search();
    });
    cms.Issuu.even();
})